package jarvis.web;

import jarvis.utils.ESClientFactory;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RegexpQueryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@Controller
public class Searchcontroller {

	private ObjectMapper om = new ObjectMapper();
	private Client esclient = ESClientFactory.getClient();

	public Searchcontroller() {
		om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	}

	@RequestMapping("/search")
	@ResponseBody
	public Object search(@RequestParam("query") String query) {
		System.out.println(query);
		SearchResponse response = null;
		if (query.startsWith("regexp:")) {
			query = query.substring("regexp:".length());
			response = esclient.prepareSearch("jarvis").setTypes("filedata")
					.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
					.setQuery(new RegexpQueryBuilder("text", query)).setFrom(0)
					.setSize(60).setExplain(true).execute().actionGet();
		} else {
			response = esclient.prepareSearch("jarvis").setTypes("filedata")
					.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
					.setQuery(QueryBuilders.termsQuery("text", query))
					.setFrom(0).setSize(60).setExplain(true).execute()
					.actionGet();
		}
		JsonNode json = response != null ? om.convertValue(response,
				JsonNode.class) : null;
		return json;
	}

	@RequestMapping("/incomplete")
	@ResponseBody
	public Object findCorrupted() {
		SearchResponse response = esclient.prepareSearch("jarvis")
				.setTypes("filedata")
				.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				.setQuery(QueryBuilders.termsQuery("validDoc", "false"))
				.setFrom(0).setSize(60).setExplain(true).execute().actionGet();
		return response;
	}

}
